<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="outLoad">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <!-- :default-sort="{prop: 'timeOfEntry', order: 'descending'} 指定默认排序的那一列是升序还是降序 -->
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber">
            <el-table-column label="聘用形式" prop="formOfEmployment">
              <template #default="{row}">
                {{ formate(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column
              label="部门"
              prop="departmentName"
            />
            <!-- sortable设置要排序的那一列 -->
            <el-table-column
              label="入职时间"
              prop="timeOfEntry"
              sortable
            />
            <el-table-column label="账户状态" />
            <el-table-column label="操作" width="280">
              <template #default="{row}">
                <el-button type="text" size="small" @click="$router.push(`/detail/${row.id}`)">查看</el-button>
                <el-button type="text" size="small" @click="AssignU(row.id)">分配角色</el-button>
                <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table-column></el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工dialog -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hClose"
      >
        <EmpDialog ref="addDialog" @success="hSuccess" @close="showDialog=false" />
      </el-dialog>
      <!-- 分配角色dialog -->
      <el-dialog title="分配角色" :visible.sync="showRoleDialog">
        <!-- 父传子 将id传给子 -->
        <AssignRole v-if="showRoleDialog" :role-id="roleId" @close="showRoleDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import AssignRole from './assignRole.vue'
import PageTools from '@/components/PageTools'
import { getEmployees, delEmployees } from '@/api/employees'
import EmpDialog from './empDialog.vue'
import Employees from '@/constant/employees'
// 枚举
const hireType = {}
Employees.hireType.forEach(item => {
  hireType[item.id] = item.value
})
export default {
  components: {
    PageTools,
    EmpDialog,
    AssignRole
  },
  data() {
    return {
      roleId: '',
      showRoleDialog: false,
      showDialog: false,
      list: [], // 存储获取的员工信息
      page: 1, // 页码值
      size: 2, // 每页显示的条数
      total: 0 // 获取的数据总数
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    AssignU(id) {
      this.roleId = id
      this.showRoleDialog = true
    },
    // 导出员工信息
    async outLoad() {
      try {
        const res = await getEmployees(this.page, this.size)
        const { headers, data } = this.outExcel(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header: headers, // ['姓名','年龄']
            data, // [['张三',15],['李四',26]]
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 封装excel导出的方法 将英文key 转换为中文key
    outExcel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 获取中文头
      let headers = []
      headers = Object.keys(list[0]).map(item => mapInfo[item])
      const data = list.map(item => {
        return Object.values(item)
      })
      return { headers, data }
    },
    // 删除员工基本信息
    hDel(id) {
      this.$confirm('你确定要删除这条数据吗?').then(async() => {
        const res = await delEmployees(id)
        if (res.code !== 10000) return
        this.$message.success(res.message)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployees()
      }).catch(err => console.log(err))
    },
    // 关闭Dialog触发的事件
    hClose() {
      this.$refs.addDialog.reForm()
    },
    // 添加员工信息
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    // 聘用形式格式化
    formate(data) {
      return hireType[data] || '未知'
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 加载员工基本信息
    async loadEmployees() {
      const res = await getEmployees(this.page, this.size)
      console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>
